package com.briup.njf;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;

public class Test5_HttpClient {
    //1.同步请求
    public static void main(String[] args) throws Exception {
        // 初始化客户端
        HttpClient client = HttpClient.newHttpClient();
        // 定义请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://www.jd.com"))
                .build();
        // 定义响应
        HttpResponse<String> response =
                client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status code: " + response.statusCode());
        System.out.println("Response body: " + response.body());
    }

    //2.异步请求
    public static void main02(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://example.com"))
                .build();

        CompletableFuture<HttpResponse<String>> future =
                client.sendAsync(request, HttpResponse.BodyHandlers.ofString());

        // 处理结果
        future.thenApply(HttpResponse::body)
                .thenAccept(System.out::println);

        // 防止主线程提前结束
        Thread.sleep(1000);
    }
}
